package com.linwancun.lwcyback.controller;

import com.linwancun.lwcyback.model.Chatrecord;
import com.linwancun.lwcyback.model.Doctor;
import com.linwancun.lwcyback.model.Patient;
import com.linwancun.lwcyback.model.TokenCharactor;
import com.linwancun.lwcyback.service.ChatRecordServiceImpl;
import com.linwancun.lwcyback.service.DoctorServiceImp;
import com.linwancun.lwcyback.service.PatientServiceImp;
import com.linwancun.lwcyback.util.JsonTransformation;
import com.linwancun.lwcyback.util.Token;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.util.*;


@RestController
@EnableAutoConfiguration
/**
 *@类名 DoctorController
 *@描述：医生控制器
 *@作者：高国彬
 *@日期 2019-07-19 11:54
 *@版本:1.0
 **/

public class DoctorController {
    @Autowired(required = false)
    private DoctorServiceImp doctorService;

    @Autowired(required = false)
    private ChatRecordServiceImpl chatService;

    @Autowired(required = false)
    private PatientServiceImp patientServiceImp;

    @Autowired
    private HttpServletRequest request;

    /**
     * @return
     */
    @GetMapping("/doctor/checktoken")
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:51
     * @param
     * @return java.lang.String
     * @throws
     * @since
     */

    public String checktoken() {
        try {
            Doctor doctor = new Doctor();
            String jwt = (String) request.getHeader("token");
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary("4234dfasdfqdd"))
                    .parseClaimsJws(jwt).getBody();
            doctor.setDoctoraccountnumber(claims.getId());
            System.out.println(claims.getId());

            Doctor foundDoctor = doctorService.find(doctor);
            String subject = claims.getSubject();

            if (foundDoctor == null && !subject.equals("doctor") && claims.getExpiration().before(new Date())) {
                return "404";
            }
            return JsonTransformation.objectToJson(foundDoctor);
        } catch (Exception e) {
            return "404";

        }

    }

    //登录，验证账号密码是否正确
    @PostMapping("/doctor/login")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:52
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String doctorLogin(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        Doctor foundDoctor = doctorService.find(doctor);
        Token t = new Token();

        String jwt = t.createJWT(doctor.getDoctoraccountnumber(), "lwcy", "doctor", 60 * 60 * 24 * 3);

        TokenCharactor tokenCharactor = JsonTransformation.jsonToObject(str, TokenCharactor.class);
        tokenCharactor.setDoctor(foundDoctor);
        tokenCharactor.setToken(jwt);

        if (foundDoctor == null) {
            return "404";
        }
        return JsonTransformation.objectToJson(tokenCharactor);
    }

    @PostMapping("/doctor/forgetpassword")
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:54
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String forgetpassword(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        try {
            Doctor newdoctor = new Doctor();
            newdoctor.setDoctoraccountnumber(doctor.getDoctoraccountnumber());
            Doctor referdoctor = doctorService.find(newdoctor);
            if (referdoctor == null) {
                return "404";
            }
            referdoctor.setDoctorpassword(doctor.getDoctorpassword());
            doctorService.save(referdoctor);
            return "200";
        } catch (Exception e) {
            return "404";
        }
    }

    //忘记密码后更新医生账号信息
    @PostMapping("/doctor/updatedoctorinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String updateDoctorInfo(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        try {
            doctorService.save(doctor);
        } catch (Exception e) {
            return "404";
        }
        return "200";
    }

    //注册，添加医生个人信息
    @PostMapping("/doctor/insertdoctorinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String insertDoctorInfo(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        try {
            doctorService.insert(doctor);
        } catch (Exception e) {
            return "404";
        }
        return "200";
    }

    //获取医生信息
    @PostMapping("/doctor/getdoctorinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param null
     * @return
     * @throws
     * @since
     */

    public String getDoctorInfo(@RequestBody String str) {
        Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
        Doctor foundDoctor = doctorService.find(doctor);
        if (foundDoctor == null) {
            return "404";
        }
        String doctorInfor = JsonTransformation.objectToJson(doctor);
        return doctorInfor;
    }

    //添加聊天记录
    @PostMapping("/doctor/chat")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String chat(@RequestBody String str) {
        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        try {
            chatService.insert(chatrecord);
            Chatrecord newchatrequest = new Chatrecord();
            newchatrequest.setPatientid(chatrecord.getPatientid());
            newchatrequest.setDoctorid(chatrecord.getDoctorid());
            return JsonTransformation.listToJson(chatService.getList(newchatrequest));
        } catch (Exception e) {
            return "404";
        }

    }

    @PostMapping("/doctor/getchatedpatients")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getchatedpatient(@RequestBody String str) {
        try {
            Doctor doctor = JsonTransformation.jsonToObject(str, Doctor.class);
            Chatrecord chatrecord = new Chatrecord();
            chatrecord.setDoctorid(doctor.getDoctorid());
            List<Chatrecord> chatrecordList = chatService.getList(chatrecord);
            Set<Integer> set = new HashSet<>();

            Iterator<Chatrecord> iterator = chatrecordList.iterator();
            List<Patient> patientList = new ArrayList<>();

            while (iterator.hasNext()) {
                Chatrecord chatrecord1 = iterator.next();
                if (set.contains(chatrecord1.getPatientid())) {
                    continue;
                }
                set.add(chatrecord1.getPatientid());
                Patient patient = new Patient();
                patient.setPatientid(chatrecord1.getPatientid());
                patientList.add(patientServiceImp.find(patient));
            }
            return JsonTransformation.listToJson(patientList);
        } catch (Exception e) {
            return "404";
        }
    }

    @PostMapping("/doctor/getnewchat")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getnewchat(@RequestBody String str) {

        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        chatrecord.setIsread(0);
        try {
            return JsonTransformation.listToJson(chatService.getNewRecord(chatrecord));
        } catch (Exception e) {
            return "404";
        }
    }

    //获取聊天记录
    @PostMapping("/doctor/getchatinfo")
    @ResponseBody
    /*
     * @作者 高国彬
     * @日期 2019-07-19 11:53
     * @param str
     * @return java.lang.String
     * @throws
     * @since
     */

    public String getChatInfo(@RequestBody String str) {
        Chatrecord chatrecord = JsonTransformation.jsonToObject(str, Chatrecord.class);
        try {
            List<Chatrecord> chatrecordList = chatService.getList(chatrecord);
            String chatList = JsonTransformation.listToJson(chatrecordList);
            return chatList;
        } catch (Exception e) {
            return "404";
        }
    }
}
